﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CroppingImageInvestigation.Controllers
{
	public class HomeController : Controller
	{
		public ActionResult Index()
		{
			ViewBag.Message = "Select area";
			ViewBag.Cropped = false;
			return View();
		}

		[HttpPost]
		public ActionResult Index(int? x, int? y, int? height, int? width)
		{
			ViewBag.Message = "Select area";
			var img = Image.FromFile(@"D:\Projects\CroppingImageInvestigation\CroppingImageInvestigation\Content\Obama.jpg");
			var bmpImage = new Bitmap(img);
			img.Dispose();
			var cropRect = new Rectangle(x.Value, y.Value, width.Value, height.Value);
			var croppedBmpImage = bmpImage.Clone(cropRect, PixelFormat.Format24bppRgb);
			SaveJpg(@"D:\Projects\CroppingImageInvestigation\CroppingImageInvestigation\Content\Obama_min.jpg", croppedBmpImage);
			ViewBag.Cropped = true;
			return View();
		}

		

		private void SaveJpg(string path, Bitmap image)
		{
			var encoderParameter = new EncoderParameter(Encoder.Quality, 100L);
			var encoder = GetEncoder("image/jpeg");

			if(encoder == null)
				return;

			var encoderParams = new EncoderParameters(1);
			encoderParams.Param[0] = encoderParameter;
			image.Save(path, encoder, encoderParams);
		}

		private ImageCodecInfo GetEncoder(string mime)
		{
			var imageCodecs = ImageCodecInfo.GetImageEncoders();
			foreach (var imageCodecInfo in imageCodecs)
			{
				if (imageCodecInfo.MimeType == mime)
				{
					return imageCodecInfo;
				}
			}
			return null;
		}

		public ActionResult About()
		{
			return View();
		}
	}
}
